#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "consts.h"
#include "common.h"
#include "function.h"
#include "syscall.h"
#include "init.h"

void init_structs(const char* file)
{
    int i;
    device_list[0].device_type = block_device;
    device_list[0].device_size = filesys.n_total_blks;
    strcpy(device_list[0].dev_description, file);

    for (i=0; i<DAT_BF_SIZE; i++)
    {
        bflist[i].block_no = -1;
        bflist[i].buffer_index = i;
    }

    freelist.last = &freelist; freelist.next = &freelist;
    busylist.last = &busylist; busylist.next = &busylist;

    for (i=0; i<DAT_BF_SIZE; i++)
    {
        list_append( &freelist, &bflist[i]);
    }

    for (i=0; i<INODE_BF_SIZE; i++)
    {
    	inode_buffers[i].count = 0;
    	inode_buffers[i].i_no_disk = -1;
    }

    for (i=0; i<FH_SIZE; i++){
        file_handles[i].inode_no = -1;
    }
}

static void init_home()
{
    int i;

    current_dir.dir = (char*)malloc( 512 );
    current_dir.size = 512;
    current_dir.len = 1;
    strcpy(current_dir.dir, "/");
    current_dir.ino = 0;
}

void init(const char* file)
{
    FILE* fp ;

	if ( file==NULL )
		file = "a.system";
	
	fp = fopen(file, "rb");
    if ( fp == NULL )
        panic("File system load error.");

    fread(&filesys, sizeof(filesys), 1, fp);

    fclose(fp);
    init_structs(file);
    init_home();
	
	atexit( leave_system );
}
